package com.jbh.wanandroidkotlin.manager

import android.content.Context
import com.google.gson.Gson
import com.jbh.apilibrary.bean.LoginResultBean
import com.jbh.wanandroidkotlin.activity.MyApplication
import com.jbh.wanandroidkotlin.util.*

class UserInfoManager private constructor(){


    companion object{

        @JvmStatic
        fun newInstance(): UserInfoManager {
            return UserInfoManager()
        }
    }


    /**
     * 保存数据
     *
     */
    fun saveInfo(info:LoginResultBean){
        val sharedPreferences = MyApplication.ctx?.getSharedPreferences(USER_INFO,Context.MODE_PRIVATE)
        val edit= sharedPreferences?.edit()
        edit?.apply() {
            with(info){
                putBoolean(ADMIN,admin)
                putString(CHAPTER_TOPS,Gson().toJson(chapterTops))
                putInt(COIN_COUNT,coinCount)
                putString(COLLECT_ID,Gson().toJson(collectIds))
                putString(EMAIL,email)
                putString(ICON,icon)
                putInt(ID,id)
                putString(NICKNAME,nickname)
                putString(PASSWORD,password)
                putString(PUBLIC_NAME,publicName)
                putString(TOKEN,token)
                putInt(TYPE,type)
                putString(USER_NAME,username)
            }
            /*提交保存用户数据*/
            commit()
        }
    }



    /**
     * 获取缓存的数据
     *
     */
     fun userInfo():LoginResultBean?{
        val sharedPreferences = MyApplication.ctx?.getSharedPreferences(USER_INFO,Context.MODE_PRIVATE)
        sharedPreferences?.apply{
            val admin = getBoolean(ADMIN,false)
            val chapterTops=getString(CHAPTER_TOPS,"")
            val coinCount = getInt(COIN_COUNT,0)
            val collectIds = getString(COLLECT_ID,"")
            val email = getString(EMAIL,"")
            val icon = getString(ICON,"")
            val id = getInt(ID,0)
            val nickname = getString(NICKNAME,"")
            val password = getString(PASSWORD,"")
            val publicName = getString(PUBLIC_NAME,"")
            val token = getString(TOKEN,"")
            val type = getInt(TYPE,0)
            val username = getString(USER_NAME,"")
            return LoginResultBean(
                 admin,
                 null,
                 coinCount,
                 null,
                 email!!,
                 icon!!,
                 id,
                 nickname!!,
                 password!!,
                 publicName!!,
                 token!!,
                 type,
                 username!!)
        }
        return null
    }





    /**
     * 清空缓存
     */
    fun clear(){
        val sharedPreferences = MyApplication.ctx?.getSharedPreferences(USER_INFO,Context.MODE_PRIVATE)
        sharedPreferences
            ?.edit()
            ?.clear()
            ?.commit()
    }





    /**
     * 判断是否登录
     *
     */
    fun isLogin():Boolean{
        return userInfo()?.id != 0
    }
}